package cc.rengu.redp.bizimpl.upmp.service.impl;/*
package cc.rengu.redp.bizimpl.upmp.service.impl;

import cc.rengu.ecp.core.pagination.GroupPropertyFilter;
import cc.rengu.ecp.core.pagination.PropertyFilter;
import cc.rengu.ecp.core.util.Common;
import cc.rengu.ecp.platform.mcmp.entity.*;
import cc.rengu.ecp.platform.mcmp.enums.BizOprEnum;
import cc.rengu.redp.bizimpl.enums.BizDataAuditStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizDataStatusEnum;
import cc.rengu.redp.bizimpl.enums.PageOptFlagEnum;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.dao.TermModelInfoMapper;
import cc.rengu.redp.bizimpl.upmp.domain.TermModelInfo;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpOrganization;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpPrivilegeCheck;
import cc.rengu.redp.bizimpl.upmp.service.IBizTmpService;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpOrganizationService;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpPrivilegeCheckService;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpSysParamService;
import cc.rengu.redp.bizimpl.upmp.vo.OperationResult;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.bizimpl.utils.DateUtils;
import cc.rengu.redp.bizimpl.utils.GZIPUtils;
import cc.rengu.redp.common.exception.RedpException;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

*/
/**
 * 终端型号管理的服务类
 *
 * @author zhuyaping
 * @date 2016年09月06日08时23分
 *//*

@Service
@Transactional
public class TermModelNewService extends ServiceImpl<TermModelInfoMapper, TermModelInfo> {

	@Autowired
	private TransactionTemplate transactionTemplate;

	@Autowired
	private IBizTmpService bizTmpService;
	
	@Autowired
	private IUpmpSysParamService upmpSysParamService;

	@Autowired
	private IUpmpOrganizationService organizationService;

	public Map<String, Object> termmodelSelect2List(HttpServletRequest request)throws RedpException {
		UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
		String q = request.getParameter("q");
		if (null == q) {
			return null;
		}
		q=q.replaceAll("&amp;", "&");
		String[] param = q.split("&");

		if (null != param && param.length > 0) {
			request.setAttribute("search['BW_modelName_OR_modelCode']", param[0]);
		}
		if (null != param && param.length > 1) {
			request.setAttribute("search['EQ_brandCode']", param[1]);
		}
		request.setAttribute("search['EQ_status']", BusinessContainer.data_sta_01);
		if(user.isAdmin() && param.length > 2){
			request.setAttribute("search['EQ_instId']", param[2]);
		}else {
			request.setAttribute("search['IN_crtOrgId']", GZIPUtils.uncompressToString(user.getUserOrgCodes()));
		}
		GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildFromHttpRequest(TermModelInfo.class, request);
		Pageable pageable = (Pageable) PropertyFilter.buildPageableFromHttpRequest(request);
		*/
/*
		 * 构建pageable时需要放入request里面的参数。
		 * "rows"-每页多少行；
		 * "page"-当前页；
		 * "start"-起始行（可以不提供，默认为：page * rows）
		 *//*

		Page<TermModelInfo> page = this.findByPage(groupPropertyFilter, pageable);
		List<TermModelInfo> listx = page.getContent();
		Map<String, Object> maps = new HashMap<String, Object>();
		Map<String, String> map = new HashMap<String, String>();
		List<Object> list = new ArrayList<Object>();
		if (listx != null) {
			for (int i = 0; i < listx.size(); i++) {
				TermModelInfo tm = listx.get(i);
				map = new HashMap<String, String>();
				map.put("id", tm.getModelCode());
				map.put("name", tm.getModelName());

				// map.put("desc", tm.getModelDesc());
				list.add(map);
			}
			maps.put("results", list);
			maps.put("more", false);
		}
		return maps;
	}

	public List<String> findAllmodelCd()throws RedpException {
		return termModelNewDao.findAllmodelCd();
	}

	public List<String> findAllmodelCdName(String modelCd, String modelName) {
		return termModelNewDao.findAllmodelCdName(modelCd, modelName);
	}
	public List<String> findAllmodelName()throws RedpException {
		return termModelNewDao.findAllmodelName();
	}

	public TermModelInfo findTermModel(String modelCode)throws RedpException {
		// TODO Auto-generated method stub
		return termModelNewDao.findmodelCode(modelCode);
	}
	public TermModelInfo findTermModelByName(String modelName)throws RedpException {
		return termModelNewDao.findModelByName(modelName);
	}

	public OperationResult saveData(String oprMenuId, String oprMenuName, TermModelInfo entity, UpmpUserInfoVO user, UpmpOrganization org, IUpmpPrivilegeCheckService authPrivilegeCheckService, HttpServletRequest request, String webNextUrl) throws RedpException {
		String flag = request.getParameter("optFlag");
		Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
		String lastUpddt = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
		String id = request.getParameter("id");
		TermModelInfo oldEntity = null;
		if (!PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(flag)){
			oldEntity = termModelNewDao.getById(id);
		}
		if (PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(flag)) {
			entity.setId(null);
			UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "终端型号管理:新增");
			if (null!=privilegeCheck&&BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
				//需要审核
				entity.setOprId(user.getId());
				entity.setCrtOrgId(org.getOrgCode());
				entity.setCreateTime(lastUpddt);
				entity.setStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
				entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType());
				(entity);

				bizTmpService.saveBizTmp(entity, user, org.getInstId(), BizOprEnum.OPR_ADD.getType(), lastUpddt
						, oprMenuId, oprMenuName, entity.getStatus(), entity.getAuditStatus(), String.valueOf(entity.getId()), webNextUrl,null,null,null);
				result.put("id", entity.getId());
			} else {
				//不需要审核
				entity.setOprId(user.getId());
				entity.setCrtOrgId(org.getOrgCode());
				entity.setCreateTime(lastUpddt);
				entity.setStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
				entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
				save(entity);

				bizHisService.saveBizHisNew(entity,entity, user, org.getInstId(), BizOprEnum.OPR_ADD.getType(), lastUpddt
						, oprMenuId, oprMenuName, String.valueOf(entity.getId()),null,null,null);
//				bizTmpService.saveBizHis(entity, user, org.getInstId(), BizOprEnum.OPR_ADD.getType(), lastUpddt
//						, oprMenuId, oprMenuName, String.valueOf(entity.getId()),null,null,null);
				result.put("id", entity.getId());
			}
		} else if (PageOptFlagEnum.OPT_FLAG_UPDATE.getType().equals(flag)) {
			if (Common.isBlank(id)) {
				 log.error("请求参数(id)异常!");
				return OperationResult.buildFailureResult("请求参数(id)异常!", result);
			}

			UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "终端型号管理:修改");
			if (null!=privilegeCheck&&BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
				//需要审核
				entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
				entity.setLastOprId(user.getId());
				entity.setLastUpdateTime(lastUpddt);
				termModelNewDao.updateAuditStatus(id,entity.getAuditStatus());//只修改状态
//				TermModelInfo termModel = termModelNewDao.getById(id);
//				BeanUtils.copyProperties(entity, termModel);
//				termModelNewDao.save(termModel);

				bizTmpService.saveBizTmp(entity, user, org.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt
						, oprMenuId, oprMenuName, entity.getStatus(), entity.getAuditStatus(), String.valueOf(entity.getId()), webNextUrl,null,null,null);
				result.put("id", entity.getId());
			} else {
				entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
				entity.setLastOprId(user.getId());
				entity.setLastUpdateTime(lastUpddt);
				TermModelInfo termModel = termModelNewDao.getById(id);
				BeanUtils.copyProperties(entity, termModel);
				termModelNewDao.save(termModel);

				bizHisService.saveBizHisNew(termModel,oldEntity, user, org.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt
						, oprMenuId, oprMenuName, String.valueOf(termModel.getId()),null,null,null);
//				bizTmpService.saveBizHis(termModel, user, org.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt
//						, oprMenuId, oprMenuName, String.valueOf(termModel.getId()),null,null,null);
			}
		} else if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(flag)) {
			if (Common.isBlank(id)) {
				 log.error("请求参数(id)异常!");
				return OperationResult.buildFailureResult("请求参数(id)异常!", result);
			}
			//获取临时表数据并转换成实体对象
			BizTmp tmp = bizTmpService.getById(id);
			if (Common.isBlank(tmp)) {
				 log.error("根据id没有找到指定临时表数据！");
				return OperationResult.buildFailureResult("根据id没有找到指定临时表数据！", result);
			}
			String bizdata = "";
			if (null != tmp.getBizData1()) {
				bizdata += tmp.getBizData1();
			}
			if (null != tmp.getBizData2()) {
				bizdata += tmp.getBizData2();
			}
			if (null != tmp.getBizData3()) {
				bizdata += tmp.getBizData3();
			}

			TermModelInfo termModelNew = JSON.parseObject(bizdata, TermModelInfo.class);

			TermModelInfo termModel = termModelNewDao.getById(id);
			// 备份正式表数据
			TermModelInfo termModelOld = new TermModelInfo();
			BeanUtils.copyProperties(termModel, termModelOld);
			if (Common.isBlank(termModel) && !BizOprEnum.OPR_ADD.equals(tmp.getBizOpr())) {
				 log.error("根据id没有找到指定数据！");
				return OperationResult.buildFailureResult("根据id没有找到指定数据！", result);
			}

			String opt = request.getParameter("opt");
			if (Common.isBlank(opt)) {
				 log.error("请求参数(opt)异常!");
				return OperationResult.buildFailureResult("请求参数(opt)异常!", result);
			}
			String bizOpr = "";
			if (BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType().equals(termModel.getAuditStatus())) {
				if (!PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {

				} else{
					BeanUtils.copyProperties(termModelNew, termModel);
				}
			}else{
				BeanUtils.copyProperties(termModelNew, termModel);
			}

			String auditRefuseReason = request.getParameter("auditRefuseReason");
			if (BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType().equals(termModel.getAuditStatus())) {
				if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
					termModel.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
					termModel.setStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
				} else {
					termModel.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_REJECT.getType());
				}
				bizOpr = BizOprEnum.OPR_ADD.getType();
			} else if (BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType().equals(termModel.getAuditStatus())) {
				if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
					termModel.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
					termModel.setStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
				} else {
					termModel.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_REJECT.getType());
				}
				bizOpr = BizOprEnum.OPR_UPDATE.getType();
			}
			termModel.setAuditRefuseReason(auditRefuseReason);
			termModelNewDao.save(termModel);
			if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
				//审批通过将正式表更新到历史表
				bizHisService.saveBizHisNew(termModel,termModelOld, user, org.getInstId(), bizOpr, lastUpddt
						, oprMenuId, oprMenuName, String.valueOf(termModel.getId()),null,null,null);
//				bizTmpService.saveBizHis(termModel, user, org.getInstId(), bizOpr, lastUpddt, oprMenuId, oprMenuName, String.valueOf(termModel.getId()),null,null,null);
			}
			// 修改临时表的审核状态等字段
			bizTmpService.saveBizTmp(termModel, user, org.getInstId(), bizOpr, lastUpddt, oprMenuId, oprMenuName, termModel.getStatus(), termModel.getAuditStatus(), String.valueOf(termModel.getId()), webNextUrl,null,null,null);
		}

		return OperationResult.buildSuccessResult("数据保存处理完成", result);
	}


	@Transactional(rollbackFor=Exception.class)
	public void saveTermModel(List<TermModelInfo> termModelList, UpmpPrivilegeCheck privilegeCheck,String brandCode,Long oprMenuId,String oprMenuName,String webNextUrl)throws RedpException{
		transactionTemplate.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus arg0) {
				if (null != termModelList && termModelList.size() > 0) {
					 UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
					SimpleDateFormat fmtdt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
					UpmpOrganization org = organizationService.getOrgByCode(user.getOrgCode(), user.getInstId());
					for (TermModelInfo termModel : termModelList) {
						String lastUpddt = fmtdt.format(new Date());
						String modelCode = getNextmodelCd(BusinessContainer.COMM_PARAM_CODE, "MDmodelCd");
						//终端品牌基本信息
						termModel.setModelCode(modelCode);
						termModel.setInstId(user.getInstId());
						termModel.setOprId(user.getId());
						termModel.setCrtOrgId(user.getOrgCode());
						termModel.setBrandCode(brandCode);
						termModel.setCreateTime(lastUpddt);
						if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
							//需要审核
							termModel.setStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
							termModel.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType());
							if (termModel.getBrandCode() != null && termModel.getModelCode() != null) {
								save(termModel);
							}
							bizTmpService.saveBizTmp(termModel, user, org.getInstId(), BizOprEnum.OPR_ADD.getType(), lastUpddt
									, String.valueOf(oprMenuId), oprMenuName, termModel.getStatus(), termModel.getAuditStatus(), String.valueOf(termModel.getId()), webNextUrl, null, null, null);
						} else {
							//不需要审核
							termModel.setStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
							termModel.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
							if (termModel.getBrandCode() != null && termModel.getModelCode() != null) {
								save(termModel);
							}
							bizHisService.saveBizHisNew(termModel, termModel, user, org.getInstId(), BizOprEnum.OPR_ADD.getType(), lastUpddt, String.valueOf(oprMenuId), oprMenuName, String.valueOf(termModel.getId()), null, null, null);
						}
					}
				}
			}
		});
	}

	public List<Map> selectTermModel(String brandCode,String modelCode,HttpServletRequest request) {
		String instId = request.getParameter("instId");
		 UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
		if(!user.isAdmin()){
			instId = user.getInstId();
		}
		StringBuffer sql = new StringBuffer("select MODEL_CODE, MODEL_NAME from T_B_TERM_MODEL_INFO where INST_ID = '"+instId+"' and STATUS = '01' ");
		if (StringUtils.isNotBlank(modelCode)){
			sql.append("and MODEL_CODE = '"+modelCode+"' ");
		}
		if (StringUtils.isNotBlank(brandCode)){
			sql.append("and BRAND_CODE = '"+brandCode+"' ");
		}
		if(!user.isAdmin()){
			sql.append("and CRT_ORG_ID = '"+user.getOrgCode()+"' ");
		}
		Query query = this.getEntityManager().createNativeQuery(sql.toString());
		query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		List<Map> list = query.getResultList();
		return list;
	}

	public Map<String, List<String>> getTermModels(List listBrandCode,HttpServletRequest request){
		Map<String, List<String>> siteMap = new HashMap<String, List<String>>();
		for(int p=0;p<listBrandCode.size();p++){
			Map mapBrandCode = (Map) listBrandCode.get(p);
			String brandCode = (String) mapBrandCode.get("BRAND_CODE");
			String brandName = (String) mapBrandCode.get("BRAND_NAME");
			List<Map> listTermModel = selectTermModel(brandCode,"",request);
			List<String> termModelList = new ArrayList<>();
			if(null != listTermModel && listTermModel.size() > 0){
				listTermModel.forEach((e) -> {
					termModelList.add(e.get("MODEL_CODE") + "-" + e.get("MODEL_NAME"));
				});
				siteMap.put(brandName, termModelList);
			}
		}
		return siteMap;
	}

	*/
/**
	 * 获取终端型号代码
	 * @param merInnerCd
	 * @param merOrder
	 * @return
	 *//*

	private String getNextmodelCd(String merInnerCd, String merOrder) throws RedpException {
		String chan = CommonUtils.getChannelId(datadictService);
		String index = String.format("%06d", Integer.parseInt(upmpSysSeqService.updateParamValue(merInnerCd, merOrder, chan)));
		return BusinessContainer.ModelCd_PREFIX + index;
	}

}
*/
